<?php
/**
 * @class StreamController
 * @name 直播stream 接口类方法
 * @author martinsun syh@sunyonghong.com
 */
namespace app\stream\controller;

use \Qiniu\Pili\Mac;
use \Qiniu\Pili\Utils;
use \Qiniu\Pili\Transport;
use app\common\controller\ZhiboV2;

class Stream extends ZhiboV2 {
	protected $mod = '';
	protected static $stream_title = ''; //初始化标题
	protected $stream_list_sort = ['airtime', 'online']; //筛选列表排序字段
	/**
	 * @name 初始化方法
	 */
	protected function _initialize() {
		parent::_initialize();
		$this->mod = model('stream/Stream');
        model('open/UserData')->checkUserData($this->uid);
	}
	/**
	 * @name 设置用户的stream标题信息
	 * @access protected
	 * @static string $stream_title
	 */
	protected function _setStreamTtile($title = '') {
		self::$stream_title = model('open/User')->getUsidByUid($this->uid) ?: $this->uid;
	}
	/**
	 * @name 获得单个用户的stream信息(不存在的情况下会自动创建一个) -- 针对主播
	 * @access public
	 * @return array 单个的stream初始信息
	 */
	public function getStream() {
		if (self::checkApi() !== true) {
			return $this->api_info;
		}

        model('open/UserData')->checkUserData($this->uid);

		//权限检测通过,获取用户的直播间
		$data = self::_getOneStream($this->uid, 'array');
		//已经创建了直播间
		if ($data) {
			if (!$data['id']) {
				return getApiErrorCode('20001');
			}
			if ($this->mod->getFieldByUid($this->uid, 'stream_icon') > 0) {
				$this->mod->update(['stream_icon' => 0], ['uid' => $this->uid]);
			}
			if ($data['im']->cid > 0) {
				return ['code' => '00000', 'data' => ['id' => $data['id'], 'im' => $data['im']]];
			}
			return getApiErrorCode('20001');
		}

		//没有创建直播间,创建一个直播间
		$hub = parent::getHub();

		$this->_setStreamTtile();

		// 先查看流信息
		$stream = self::_getStreamInfo($hub, self::_getStreamTitle());

		// 如果没有，创建
		if (!$stream) {
			$stream = self::_createStream($hub, self::_getStreamTitle());
			$add = [
				'uid' => intval($this->uid),
				'stream_id' => $stream['key'],
				'stream_hub' => $config_hub
			];

			$re = $this->mod->add($add);

			if (!$res) {
				return getApiErrorCode('20001');
			}

			//再次获取新的直播间
			$data = self::_getOneStream($this->uid, 'array');
			//取得本次创建的直播间
			if ($data) {
				if ($data['im']->cid > 0) {
					return ['code' => '00000', 'data' => ['id' => $data['id'], 'im' => $data['im']]];
				}
			}
			// return [
			// 	'code' => '00000',
			// 	'data' => [
			// 		'id' => $data['id'],
			// 		'im' => $data['im']
			// 	]
			// ];
		}

		//再次获取新的直播间
		$data = self::_getOneStream($this->uid, 'array');
		//取得本次创建的直播间
		if ($data) {
			if ($data['im']->cid > 0) {
				return ['code' => '00000', 'data' => ['id' => $data['id'], 'im' => $data['im']]];
			}
		}

		// return [
		// 	'code' => '00000',
		// 	'data' => [
		// 		'id' => $data['id'],
		// 		'im' => $data['im']
		// 	]
		// ];
	}
	/**
	 * @name 校验stream_id
	 * @access public
	 * @param string stream_id  MD5加密的流ID
	 * @return array 验证结果
	 */
	public function checkStream() {
		$st = self::checkApi(['stream_id']);
		if ($st !== true) {
			return $this->api_info;
		}

		$stream_id = $this->mod->getStreamId($this->uid);
		//不存在的直播间
		if (!$stream_id || strtolower(md5($stream_id)) != strtolower($this->stream_id)) {
			return getApiErrorCode('60404');
		}
		//直播间存在,检验直播间信息
		if ($this->mod->getStreamStatus($this->uid) === 0) {
			//被禁播
			$re = $this->mod->getDisable($this->uid);
			if ($re === 2) {
				//需要更新流信息
				$this->enable('', true);
			} elseif (is_array($re)) {
				return $re;
			}
		}
		$stream = self::_getOneStream('', 'array');

		// 用户被禁播
		if ($stream['disabledTill'] === -1 || $stream['disabledTill'] > NOW_TIME) {
			return getApiErrorCode('60000');
		}

		$stream_service 	= model('admin/Config')->getConfigValue(['type'=>'stream','key'=>'stream_service']);
		$ak 				= $stream_service['qiniu_accessKey'];
		$sk 				= $stream_service['qiniu_secretKey'];
		$hubName 			= $stream_service['hub_name'];

		$publish 			= \Qiniu\Pili\RTMPPublishURL(C('qiniu.rtmp-push'), $hubName, $stream['id'], 3600, $ak, $sk);
			$stream['hosts'] 	= [
				// "hdl" 		=> \Qiniu\Pili\HDLPlayURL("live-hdl.zhiyicx.com", $hubName, $stream['id']),
    //             "hls" 		=> \Qiniu\Pili\HLSPlayURL("live-hls.zhiyicx.com", $hubName, $stream['id']),
                "rtmp" 		=> \Qiniu\Pili\RTMPPlayURL(C('qiniu.rtmp-play'), $hubName, $stream['id'])
			];

		return ['code' => '00000', 'data' => ['stream' => $stream, 'publish' => $publish ] ];
		//}
		//有效性检验失败,返回初始化失败
		// return getApiErrorCode('60001');

	}
    	/**
	 * @name 重新激活(解除禁播)
	 * @access public
	 * @param int|string $uid (from api data) 用户的uid
	 * @return array 返回设置后的单个stream
	 */
	public function enable($stream = false, $get = true) {
		$stream = $stream ? $stream : self::checkApi(true);
		if (is_array($stream) && $stream['code']) {
			return $stream;
		}

		$stream->enable();
        $this->mod->update(['status' => 2], ['uid' => $this->uid]);
		//缓存清理
		self::_cleanstream($this->uid);
		if ($get == true) {
			$stream = self::_getOneStream('', 'array');
			return ['code' => '00000', 'data' => $stream];
		}
		return true;
	}
	/**
	 * @name 开始推流
	 * @access public
	 * @param string title 房间标题信息
	 * @param object icon 二进制文件资源
	 * @param string location地址
	 * @return array 结果数据
	 */
	public function startStream() {
		$st = self::checkApi();
		if ($st !== true) {
			return $this->api_info;
		}
		$title = str_replace('"', '', $this->data['title']);
		$update['stream_title'] = $title ? formatEmoji($title, true) : '';
		if ($this->data['location']) {
			$update['location'] = self::_getLocation($this->data['location']);
		}else{
		    $update['location'] = '';
		}
		if (!$update['stream_title']) {
			$update['stream_title'] = formatEmoji(model('open/User')->getUsername($this->uid), true);
		}
		$this->mod->update($update, ['uid' => $this->uid]);
		//添加缓存表,后续需要在回调的时候再添加!!!!!!!!!!
		$tmp = $this->mod->addAnchorTmp($this->uid);
		//清理缓存
		self::_cleanstream($this->uid);
		if ($tmp) {
			$stream = self::_getOneStream('', 'array');
			// 直播商品
			if ($this->data['shop']) {
				$shopData['stream_id'] = $stream['id'];
				$shopData['shop_name'] = $this->data['shop_name'];
				$shopData['shop_cover'] = decrypt_id($this->data['shop_cover']);
				$shopData['shop_link'] = $this->data['shop_link'];
				$shopData['shop_price'] = $this->data['shop_price'];
				$shopData['uid'] = $this->uid;
				$shopData['create_time'] = time();
				if (!($shopData = model('stream/StreamShop')->getInstance()->add($shopData))) {
					return ['code' => '90001', 'message' => model('stream/StreamShop')->getInstance()->getError()];
				}
			} else {
				model('stream/StreamShop')->getInstance()->unStreamId($stream['id']);
			}

			// 用户被禁播
			if ($stream['disabledTill'] === -1 || $stream['disabledTill'] > NOW_TIME) {
				return getApiErrorCode('60000');
			}

			$stream_service 	= model('admin/Config')->getConfigValue(['type'=>'stream','key'=>'stream_service']);
			$ak 				= $stream_service['qiniu_accessKey'];
			$sk 				= $stream_service['qiniu_secretKey'];
			$hubName 			= $stream_service['hub_name'];
			$publish 			= \Qiniu\Pili\RTMPPublishURL(C('qiniu.rtmp-push'), $hubName, $stream['id'], 3600, $ak, $sk);
			$stream['hosts'] 	= [
				// "hdl" 		=> \Qiniu\Pili\HDLPlayURL("live-hdl.zhiyicx.com", $hubName, $stream['id']),
    //             "hls" 		=> \Qiniu\Pili\HLSPlayURL("live-hls.zhiyicx.com", $hubName, $stream['id']),
                "rtmp" 		=> \Qiniu\Pili\RTMPPlayURL(C('qiniu.rtmp-play'), $hubName, $stream['id'])
			];

			return ['code' => '00000', 'data' => ['stream' => $stream, 'publish' => $publish ] ];
		}
		return getApiErrorCode('60001');
	}
	/**
	 * @name 结束推流
	 * @access public
	 * @param string stream_id MD5加密的流ID
	 * @return array 结果信息
	 */
	public function endStream() {
		$st = self::checkApi(['stream_id']);
		if (true !== $st) {
			return $this->api_info;
		}

		//当前流权限检验
		$stream_id = $this->mod->getStreamId($this->uid);
		if ($stream_id) {
			$token = md5($stream_id);
			if (strtolower($token) != strtolower($this->stream_id)) {
				//非法用户请求
				return getApiErrorCode('40007');
			}
			$status = $this->mod->getStreamStatus($this->uid);
			//正在直播,请求结束
			if ($status === 1) {
				//用户自己请求结束
				$update['status'] = 2;
				//更新上次播放时间
				$update['last_airtime'] = $this->mod->getFieldByUid($this->uid, 'airtime');
				$this->mod->update($update, ['uid' => $this->uid]);
                //发送通知
                $im_model = model('open/UserImAccount');
                $im = $im_model->getConversation(['uid' => $this->uid, 'affix' => $stream_id, 'type' => 2], false);
                $msg = [
                    'uid' => 10,//管理员
                    'type' => 210,
                    'rt'   => false,
                    'txt'  => '已结束直播',
                    'ext'  => [
                        'customID' => 50700,
                        'ZBUSID' => model('open/User')->getUsidByUid($this->uid),
                    ],
                    'cid' => $im['cid'],
                ];
                $rs =  $im_model->messagePOST($msg);
			}
			//清理缓存
			self::_cleanstream($this->uid);
			$data = $this->mod->getEndLiveDataDoNotClear($this->uid, true);
			//结束会话
			//self::endConversation(['uid' => $this->uid, 'affix' => $stream_id, 'type' => 2]);
			return ['code' => '00000', 'data' => $data];

		} else {
			//不存在的直播间
			return getApiErrorCode('60404');
		}
	}
	/**
	 * @name 获得直播间列表
	 * @author martinsun syh@sunyonghong.com
	 * @access public
	 * @return array 返回设置后的单个stream
	 */
	public function getList() {
		$res = self::checkApi();
		if ($res !== true) {
			return $this->api_info;
		}
		//排序方式
		if (in_array($this->order, $this->stream_list_sort)) {
			$order = $this->order;
		} else {
			$order = 'online';
		}
		//条数限制

		$limit = (int) $this->limit ? (int) $this->limit : 10;
		$timespan = S('getList_' . $this->uid . '_time');
		//每次获取第一页数据进行数据刷新
		if ($this->data[C('var_page')] == '1' || !isset($this->data[C('var_page')])) {
			S('getList_' . $this->uid . '_time', null);
			$timespan = null;
		}
		//取得该用户的获取列表时间节点
		if ($timespan) {
			$map['airtime'] = array('lt', (int) $timespan);
		} else {
			//首次/刷新操作
			$map['airtime'] = array('lt', NOW_TIME);
			S('getList_' . $this->uid . '_time', NOW_TIME);
		}
		$map = array_merge($map, self::_getFilterParam($map));
		//按条件获取正在直播的列表
		$uids = $this->mod->getList($map, $order, $limit);
		//添加一个测试禁播的用户进去
		$result = self::_getListData($uids);
		return ['code' => '00000', 'data' => $result];

	}
	/**
	 * @name 通过uid获取主播信息
	 */
	protected function _getListData($uids = []) {
		$list = [];
		if (!empty($uids)) {
		   $title = formatEmoji(model('admin/Config')->getConfigValue(['type'=>'stream','key'=>'stream_config'],'stream_title'), false) ?: '[uname]-在直播';
			foreach ($uids as $k => $v) {
				$uid = $v;
				if (!$uid) {
					continue;
				}

				$v = [];
				$stream = self::_getOneStream($uid, 'array');
				if ($stream) {
					//提取返回的数据
					$v['stream'] = [
						'id' => $stream['id'],
						'title' => $stream['title'],
						'location' => $stream['location'],
						'icon' => $stream['icon'],
						'online_count' => $stream['online_count'],
					];
					$v['im'] = $stream['im'];
					unset($stream);
					//提取用户信息
					$user = model('open/User')->getUserInfo($uid);
					$v['user'] = ['usid' => $user['usid']];
					if (!$v['stream']['title'] || $v['stream']['title'] == $user['uname']) {
						$v['stream']['title'] =  str_replace('[uname]',$user['uname'],$title);
					}

					$list[] = $v;
				}

			}
		}
		return $list;
	}
	/**
	 * 组装筛选条件
	 */
	protected function _getFilterParam($map = []) {
		//筛选条件处理
        $filter_list = model('admin/Config')->ApiServiceGetConf('filter')['live'];
        if(!empty($filter_list)){
    		foreach ($filter_list as $v) {
    			if ($this->data[$v['key']]) {
    
    				//带时间的数据单独处理
    				if (preg_match('/time/i', $v['key'])) {
    					list($start, $end) = explode(',', $this->data[$v['key']]);
    					$airtime = $map['airtime'][1];
    					$airtime = $start > $airtime ? $airtime : $start;
    					$end = ($end > NOW_TIME || !$end) ? NOW_TIME : $end;
    					$map['airtime'] = ['between', $airtime . ',' . $end];
    					continue;
    				}
    				//带地区单独处理
    				if (preg_match('/location/i', $v['key'])) {
    					if ((int) ($this->location)) {
    						$this->data['location'] = D('Area')->getAreaById($this->data['location'])['title'];
    					}
    					$this->data['location'] && $map['location'] = ['like', '%' . $this->data['location'] . '%'];
    					continue;
    				}
    				//带男女
    				if (preg_match('/sex/i', $v['key'])) {
    					if ((int) ($this->sex)) {
    						$map['sex'] = (int) $this->sex;
    					} elseif (false !== stripos($this->sex, '男')) {
    						$map['sex'] = 1;
    					} elseif (false !== stripos($this->sex, '女')) {
    						$map['sex'] = 2;
    					}
    					continue;
    				}
    				$map[$v['key']] = $this->data[$v['key']];
    			}
    		}
        }
		$map['uid'] = ['neq', $this->uid];
		return $map;
	}
	/**
	 * @name 直播结束,删除会话信息,关闭聊天室
	 */
	protected function endConversation($map = []) {
		if (!$map['uid']) {
			return 0;
		}
		return model('open/UserIm')->deleteConversation($map);
	}
	/**
	 * 根据经纬度获取地理位置信息
	 * @access protected
	 * @param string $location GPS坐标地址
	 * @return string 地址信息
	 */
	protected function _getLocation($location = '') {
		if ($location != '') {
			$location = str_replace('"', '', $location);
			$ak = C('baidu_map_ak');
			$url = 'http://api.map.baidu.com/geocoder/v2/?ak=' . $ak . '&location=' . $location . '&output=json&coordtype=wgs84ll';
			$json = file_get_contents($url);
			$res = json_decode($json, true);
			if ($res['status'] == '0') {
				$location = $res['result']['addressComponent']['province'];
				if ($location == $res['result']['addressComponent']['city']) {
					$location .= $res['result']['addressComponent']['district']; //取得区
				} else {
					$location .= $res['result']['addressComponent']['city']; //取得市
				}
			}

		}
		return $location;
	}
	/**
	 * @name 查询单个用户的stream(不存在不会自动创建,供本类调用)
	 * @access protected
	 * @param int|string $uid 用户的uid标识(自动获取当前请求用户的)
	 * @param string $type 获取的数据类型  default:object
	 * @param boolean $cahce 是否需要缓存  default:true
	 * @return object|array|boolean  查询成功返回对象 or 数组数据 or 失败返回false
	 */
	protected function _getOneStream($uid = '', $type = 'object', $cache = true) {
		$uid = $uid ? $uid : $this->uid;
		$stream = null;
		if ($stream_id = $this->mod->getStreamId($uid)) {
			//取得缓存数据
			// $stream = S('stream_' . $type . '_' . $uid);

				//获取最新的数据
			$hub = parent::getHub();
			// $stream = $hub->stream($stream_id);

			$stream = self::_getStreamInfo($hub, $stream_id);
			$streamInfo = [];
			$data = [];
			$info = $this->mod->getstreamInfo($uid, ['uid', 'stream_title', 'stream_icon', 'location'],false);
			$data['title'] = formatEmoji($info['stream_title'], false);
			$data['id'] = $stream['key'];
			//判断是否有封面图
			if ($info['stream_icon'] > 0) {
				$data['icon'] = (object) model('attach/Attach', ['getAttachUrl', $info['stream_icon']]);
				//保存封面图获取方式
				$data['icon_get_method'] = 1;
			} else {
				    //获取直播配置
                    		$config = model('admin/Config')->getConfigValue(['type'=>'stream','key'=>'stream_config']);
                    		if($config['stream_snapshot'] == 1){
                    			$data['icon'] =(object)['0' =>  \Qiniu\Pili\SnapshotPlayURL(C('qiniu.snap-shot'), $stream['hub'], $stream['key'])];

                    		}else{
                        		$data['icon'] = (object) model('attach/Attach', ['getAttachUrl', $config['stream_icon']]);
                    		}
				$data['icon_get_method'] = 2;
			}
			$data['disabledTill'] = $stream['disabledTill'];
			$data['location'] = $info['location'] ?: '';
			//当聊天室不存在的时候,是否自动创建
			$auto_create = false;
			//当前登陆的用户获取自己创建的聊天室
			if ($uid == $info['uid'] || $info['uid'] == 4) {
				$auto_create = true;
			}
			$im = model('open/UserImAccount')->getConversation(['uid' => $info['uid'], 'affix' => $stream_id, 'type' => 2], $auto_create);
			if ($im['cid'] <= 0) {
				//清理缓存
				self::_cleanstream($uid);
				return [];
			} else {
				$data['online_count'] = $im['mc'] ? (int) $im['mc'] : 0;
				unset($im['mc']);
				$data['im'] = (object) $im;
			}
			$streamInfo = $data;
			unset($data, $info); 

		} else {
			$usid = model('open/User')->getUsidByUid($uid);
			
			$hub = parent::getHub();

			$resp = $hub->create($usid);

			$stream = $hub->stream($usid);

			$stream = self::_getStreamInfo($hub, $usid);

			if ($stream) {
				$this->_setStreamTtile();
				$config_hub = model('admin/Config')->getConfigValue(['type'=>'stream','key'=>'stream_service'],'hub_name');
				//保存stream数据到本地
				$add = ['uid' => intval($uid), 'stream_id' => $usid, 'stream_hub' => $config_hub];

				$re = $this->mod->add($add);
				if (!$re) {
					return getApiErrorCode('20002');
				}

				$data['id'] = $usid;
				$im = model('open/UserImAccount')->getConversation(['uid' => $uid, 'affix' => $usid, 'type' => 2], true);

				if ($im['cid'] <= 0) {
					//清理缓存
					self::_cleanstream($uid);
					return [];
				} else {
					$data['online_count'] = $im['mc'] ? (int) $im['mc'] : 0;
					unset($im['mc']);
					$data['im'] = (object) $im;
				}

				$streamInfo = $data;
			}

		}
		return $streamInfo;
	}

	/**
	 * 获取指定直播的片段
	 */
	public function getSnapshot($stream = false, $uid = 0, $time = NOW_TIME) {
		$stream = $stream ? $stream : self::_getOneStream($uid);
		$name = md5('stream_' . $this->uid . time()) . '.jpg'; // required
		$format = 'jpg'; // required
		$time = $time ? (int) $time : NOW_TIME; // optional, in second, unix timestamp
		$notifyUrl = NULL; // optional
		$pipeline = model('admin/Config')->getConfigValue(['type'=>'stream','key'=>'stream_service'],'pipeline');

		$result = $stream->snapshot($name, $format, $time, $notifyUrl, $pipeline); # => Array
		if ($result['targetUrl']) {
			return ['code' => '00000', 'data' => ['image' => (object) [$result['targetUrl']]]];
		} else {
			return ['code' => '00000', 'data' => ['image' => (object) []]];
		}
	}
    /**
     * @name 获取直播间片段
     */
    public function getSnapshotByStreamId($stream_id = 0){
        if($stream_id){
            $hub = parent::getHub();
    		$stream = $hub->stream($stream_id);
        }
        $name = md5('stream_' . $this->uid . time()) . '.jpg'; // required
		$format = 'jpg'; // required
		$time = $time ? (int) $time : NOW_TIME; // optional, in second, unix timestamp
		$notifyUrl = NULL; // optional
		$pipeline = model('admin/Config')->getConfigValue(['type'=>'stream','key'=>'stream_service'],'pipeline');

		$result = $stream->snapshot($name, $format, $time, $notifyUrl, $pipeline); # => Array
		return $result['targetUrl'] ?:'';
    }
	/**
	 * @name 清除用户的所有stream信息
	 * @access protected
	 * @param int $uid 用户UID
	 */
	protected function _cleanstream($uid) {
		$uid = $uid ? $uid : $this->uid;
		S('stream_array_' . $uid, null);
		S('stream_object_' . $uid, null);

	}
    public function getStreamClass($stream_uid = 0){
        return self::_getOneStream($stream_uid);
    }
	/**
	 * @name 获得用户的stream标题信息
	 * @access protected
	 * @static string $stream_title
	 * @return string 当前用户的标题
	 */
	protected function _getStreamTitle() {
		return self::$stream_title;
	}
	/**
	 * @name 创建单个用户的stream
	 * @access protected
	 * @param object $hub 创建的HUB类
	 * @param string $title 标题
	 * @param string $publishKey 用户的publishKey  默认采用系统的
	 * @param string $publishSecurity 用户的publishSecurity  默认采用系统的
	 * @return object|boolean  创建成功返回对象 or 失败返回false
	 */
	// protected function ($hub = '', $title = null, $publishKey = null, $publishSecurity = null) {
	// 	$hub = $hub ? $hub : parent::getHub();
	// 	$stream = $hub->createStream($title, $publishKey, $publishSecurity);
		
	// 	$stream = $stream->id ? $stream : false;
	// 	return $stream;
	// }

	// V2
	protected function _createStream($hub = '', $streamKey = '') {
		$hub 		= $hub ? $hub : parent::getHub();
		$stream 	= $hub->stream($streamKey);
		
		try {
		    $resp 	= $hub->create($streamKey);

		    return $resp->info();
		    
		} catch (\Exception $e) {
			return false;
		}
	}

	// v2 查询流
	protected function _getStreamInfo($hub = '', $streamKey = '')
	{
		$hub 		= $hub ? $hub : parent::getHub();
		$stream 	= $hub->stream($streamKey);
		try {
			return $stream->info();
		} catch ( \Exception $e) {
			$stream = $hub->create($streamKey);
            		return $stream->info();
		}
	}

    /**
     * @name 获取客户服务器的用户数据
     */
    public function checkUserData($uid = 0,$request = false){
        if(!$uid) return false;
        if($this->is_sync($uid) === 1 || $request === true){
            //$conf = C('conf_service_api.user_data_get_conf')?:'';
            
            if($conf){
                $data['usid'] = model('open/User')->getUsidByUid($uid);
                $conf['method'] = in_array($conf['method'],['get','post']) ? $conf['method'] : 'post';
                if($conf['method'] == 'post'){
                    $data = array_merge($conf['data'],$data);
                }
                if(is_array($conf['header'])){
                    $this->header = $conf['header'];
                }
                $data = self::request($conf['method'],$data,$conf['url']);
                $account = json_decode($data,true);
                if($account['status'] == 1){
                    $this->checkData($uid,$account['data']);
                    //设置为不需要同步
                    $this->setSync($uid,0);
                }
            }
        }
	}

	/**
	 * @name 推流状态回调方法-状态改变的处理方法
	 * @access public
	 * @for qiniu
	 */
	public function statusBack() {
		$id = $_GET['title'];
		$status = $_GET['live'];
		$update = [];
		if ($id) {
		$where['stream_id'] = $id;
		$uid = $this->mod->getUidByStream($where['stream_id']);
                $update = [];
		//基本验证通过
		$localStatus = $this->mod->getStreamStatus($uid);
		if ($localStatus === 0) {
			//被禁播,不做任何处理
			exit;
		}
            	//给用户服务器发送状态变更通知
            	//获取配置
            	$conf = model('admin/Config')->getConfigValue(['type'=>'sync','key'=>'stream_status_back_conf']);
            	//是否做了配置
            	if($conf['url']){
                	$data['usid'] = model('open/User')->getUsidByUid($uid);
                	$data['info'] = $status;
                	$data['status'] = ($data['info'] == 'on') ? 1 : 2;
                	$conf['method'] = in_array($conf['method'],['get','post']) ? $conf['method'] : 'post';
                	if($conf['method'] == 'post'){
                    		$data = array_merge($conf['data'],$data);
                	}
                	if(is_array($conf['header'])){
                    		$this->header = $conf['header'];
                	}
                	$this->request($conf['method'],$data,$conf['url']);
            	}
			//状态对比
		switch ($status) {
			case 'on':
				//用户已经主动触发事件
				if ($localStatus === 1) {
					break;
				}

				$update['airtime'] = NOW_TIME;
				$update['status'] = 1;
				break;
			default:
				//用户已经主动触发事件
				if ($localStatus === 2) {
					break;
				}
				$update['last_airtime'] = $this->mod->getFieldByUid($uid, 'airtime');
				$update['status'] = 2;
				$update['stream_title'] = '';
				break;
		}
		}
		//更新直播状态
		if (!empty($update) && !empty($where)) {
			$this->mod->update($update, $where);
		}
		$streamInfo = $this->mod->getstreamInfo($uid);
		//主播断开-- 异常断开
		if ($uid && $update['status'] === 2) {
            	//发送通知
            	$im_model = model('open/UserImAccount');
            	$im = $im_model->getConversation(['affix' => $where['stream_id'], 'type' => 2], false);
            	$msg = [
                	'uid' => 10,//管理员
                	'type' => 210,
                	'rt'   => false,
                	'txt'  => '已结束直播',
                	'ext'  => [
                    		'customID' => 50700,
                    		'ZBUSID' => model('open/User')->getUsidByUid($uid),
               	 	],
               	 	'cid' => $im['cid'],
            	];
            	$rs = $im_model->messagePOST($msg);
            	//结束该主播发起的投票
            	model('apps/Vote')->endVoteByUid($uid);
		$anchor_tmp = M('anchor_tmp')->field(['gold','zan_count','view_count'])->where('uid='.(int)$uid)->find();
		self::_saveStream($uid, $anchor_tmp);
		}
		//主播主动结束
		if ($localStatus === 2) {
			//保存本次播放的直播
			$anchor_tmp = M('anchor_tmp')->field(['gold','zan_count','view_count'])->where('uid='.(int)$uid)->find();
			self::_saveStream($uid, $anchor_tmp);
		}
        	//更新统计数据
        	$this->mod->updateUserData($uid);
		self::_cleanstream($uid);

	}
	// v2的保存方法
	public function _saveStream($uid = 0, $tmp_data)
	{
		$streamInfo 				= $this->mod->getstreamInfo($uid);
		if (empty($streamInfo)) {
			return;
		}
		// $streamKey 					= model('open/User')->getUsidByUid($uid);
		$streamKey 					= $streamInfo['stream_id'];
		$start 						= intval($streamInfo['airtime']);
		$end 						= NOW_TIME - 1;
		$hub 						= parent::getHub();
		$stream 					= $hub->stream($streamKey);
		$list 						= model('admin/Config')->getConfigList('video','video_config');
		
		if (!empty($list['data'])) {
			$video_config 			= $list['data'][0]['value'];
        		$video_status 			= (int)$list['data'][0]['status'];
        	} else {
        		$video_config = [
                		'video_prefix'         =>'zb_',//保存的视频前缀
                		'video_suffix'         =>'mp4',//保存的视频后缀,根据后缀名称进行转码
               			'video_effective_time' => 30,//保存的视频有效时间,单位为秒,0表示每次直播都保存
                		'video_title'          => '[uname]的视频',//设置视频的标题  [uname]会替换成用户昵称
            		];
        	}

		$options 					= [];
		$options['fname']			= $video_config['video_prefix'] . md5($start . $end . $uid) . '.' . $video_config['video_suffix'];
		$options['start']			= $start;
		$options['end'] 			= $end;
		$options['format']			= $video_config['video_suffix'];
		$options['expireDays']			= 30;
		$options['pipeline']			= 'shante';
		$options['notify']			= $_SERVER['HTTP_HOST'] . '/stream/Stream/saveBack';

		$result 				= $stream->saveas($options);
		if (!$result['persistentID']) {
			return ;
		}

		$check['video_start']			= $start;
		$check['video_end']			= $end;
		$check['video_ext']			= strtolower($video_config['video_suffix']);
		$check['uid']				= $uid;

		$video_model 				= model('stream/Video');
		// 视频已经保存过了
		if ($video_model->checksaveStream($check)) {
			return;
		}

		$add 						= [
			'persistentId' => $result['persistentID'],
			'status' => 1,
		];

		$uname 					= formatEmoji(model('open/User')->getUsername($uid, true));
		 if ($uname == $streamInfo['stream_title']) {
			$video_title_config = model('admin/Config')->getConfigValue(['type'=>'video','key'=>'video_config'],'video_title') ?: '[uname]录制的视频';
			$streamInfo['stream_title'] = str_replace('[uname]', $uname, $video_title_config); 
		}
		$add['video_icon']			= $streamInfo['stream_icon'];
		$add['video_title']			= $streamInfo['stream_title'];
		$add['from_stream']			= $streamInfo['stream_id'];
		$add['video_location']			= $streamInfo['location'];
		if (!$add['video_icon']) {
			$icon 				= $stream->snapshot([ 'fname' => md5($start . $end . $uid), 'time' => $start + 1 ]);
			$add['video_icon']		= $icon['fname'];
		}
		$add['diggs']				= $tmp_data['zan_count'] ?: 0;
		$add 						= array_merge($add, $check);
		$video 						= $video_model->addVideo($add);

		// 绑定商品
		model('stream/StreamShop')->setVideo($streamInfo['stream_id'], $video);

		$update['stream_icon']		= 0;
		$update['stream_title']		= '';
		$this->mod->update($update, ['uid' => $uid]);
		$this->mod->getEndLiveData($uid, true);
		return;
	}

	/**
	 * @name 搜索接口
	 */
	public function search($data = []) {
		$keyword = formatEmoji(string_filter($this->keyword), true);
		$keyword && $map['stream_title'] = ['like', '%' . $keyword . '%'];
		$map['status'] = 1;
		//条数限制
		$limit = (int) $this->limit ? (int) $this->limit : 10;
		$timespan = S('getSearch_' . $this->uid . '_time');
		//每次获取第一页数据进行数据刷新
		if ($this->data[C('var_page')] == '1' || !isset($this->data[C('var_page')])) {
			S('getSearch_' . $this->uid . '_time', null);
			$timespan = null;
		}
		//取得该用户的获取列表时间节点
		if ($timespan) {
			$map['airtime'] = array('lt', (int) $timespan);
		} else {
			//首次/刷新操作
			$map['airtime'] = array('lt', NOW_TIME);
			S('getSearch_' . $this->uid . '_time', NOW_TIME);
		}
		//$map['uid'] = ['neq', $this->uid];
		//按条件获取正在直播的列表
		$uids = $this->mod->getSearch($map, $limit, "locate('" . $this->keyword . "', stream_title) ASC,length(stream_title)-length('" . $this->keyword . "'),airtime desc");
		$result = self::_getListData($uids);
		return ['code' => '00000', 'data' => ['stream_list' => $result]];
	}
	/**
	 * @name 获取片段
	 */
	public function segments($stream = false) {
		if (!$stream) {
			//API请求
			$st = self::checkApi();
			if ($st !== true) {
				return $this->api_info;
			}
			$stream = self::_getOneStream($this->uid);
		}
		$segments = $stream->segments();
		return $segments;
	}
	/**
	 * @name 请求保存文件
	 * //http://api.qiniu.com/status/get/prefop?id=<persistentId>  查询地址
	 */
	public function saveStream($uid = 0) {
        $list = model('admin/Config')->getConfigList('video','video_config');
        $video_status = 1;
        if(!empty($list['data'])){
            $video_config = $list['data'][0]['value'];
            $video_status = (int)$list['data'][0]['status'];
        }else{
            $video_config = [
                'video_prefix'         =>'zb_',//保存的视频前缀
                'video_suffix'         =>'mp4',//保存的视频后缀,根据后缀名称进行转码
                'video_effective_time' => 30,//保存的视频有效时间,单位为秒,0表示每次直播都保存
                'video_title'          => '[uname]的视频',//设置视频的标题  [uname]会替换成用户昵称
            ];
        }
        //配置回放功能已经关闭
        if($video_status !== 1) return;
		if (!$uid) {
			//API请求
			$st = self::checkApi();
			if ($st !== true) {
				return $this->api_info;
			}
		}
		$uid = $uid ? (int) $uid : (int) $this->uid;
		$stream = self::_getOneStream($uid);
		//没有取得流信息
		if (!$stream) {
			return getApiErrorCode('20404');
		}

		//获取直播片段
		//$segments = self::segments($stream);
		//取得最新的流数据
		//$check['video_start'] = $start = $segments['segments']['0']['start'];
		//$check['video_end'] = $end = $segments['segments']['0']['end'];
		//检测是否为有效时间内的视频
		if ($check['video_end'] - $check['video_start'] < $video_config['video_effective_time']) {
			return;
		}
		$check['uid'] = $uid;
		//取配置的后缀
		$video_suffix = $video_config['video_suffix'];
		$video_suffix = $video_suffix ? $video_suffix : 'mp4';
		$check['video_ext'] = $format = strtolower($video_suffix);
		$video_model = model('stream/Video');
		$status = $video_model->checksaveStream($check); //true = has or false = no
		//已经存在了
		if ($status) {
			return;
		}
		//处理推流中断的视频
		//$start = M('video')->order('vid desc')->getFieldByUid($uid,'video_end') ? :$start;

		//开始命名
		$name = $start . $end . $uid; //名字主体
		//取得前缀
		$video_prefix = $video_config['video_prefix'];
		$video_prefix = $video_prefix ? $video_prefix : 'video_';
		//生成视频保存的名字
		$name = $video_prefix . md5($name) . '.' . $format;
		//回调地址
		$notifyUrl = $_SERVER['HTTP_HOST'] . '/stream/Stream/saveBack';
		//队列处理
		$pipeline = model('admin/Config')->getConfigValue(['type'=>'stream','key'=>'stream_service'],'pipeline');
		//执行保存视频
		$result = $stream->saveAs($name, $format, $start, $end, $notifyUrl, $pipeline);
        
        if (!$result['persistentId']) {
			return;
		}
		//取得本次的直播相关信息
		$data = $this->mod->getstreamInfo($uid,[],false);
		//保存结果
		$add = [
			'persistentId' => $result['persistentId'],
			'status' => 1,
		];
		if ($data) {
			$uname = formatEmoji(model('open/User')->getUsername($uid), true);
			if (!$data['stream_title'] || $uname == $data['stream_title']) {
				$data['stream_title'] = '';
			}
			$add['video_icon'] = $data['stream_icon'];
			$add['video_title'] = $data['stream_title'];
			$add['from_stream'] = $data['stream_id'];
			$add['video_location'] = $data['location'];
		}
		//截取开播时的截图
		if (!$add['video_icon']) {
			$icon = self::getSnapshot($stream, $uid, $data['airtime'])['data']['image'];
			$icon = object2array($icon);
			$add['video_icon'] = $icon[0];
		}
		$add = array_merge($add, $check);
		//添加数据
		$video = $video_model->addVideo($add);
		// 绑定商品
		model('stream/StreamShop')->getInstance()->setVideo($data['stream_id'], $video);
		$update['stream_icon'] = 0;
		$update['stream_title'] = '';
		$this->mod->update($update, ['uid' => $uid]);
		return;
	}

	/**
	 * @name 保存与转码的回调接口
	 */
	public function saveBack() {
		//接收返回数据
		$res = file_get_contents("php://input");
		$res = json_decode($res, true);
		$update = [];
		if ($res) {
			$where['persistentId'] = $res['id'];
			$item = $res['items'][0];
			$key = explode('/', $item['key']);
			if (is_array($key) && !empty($key)) {
				$update['video_path'] = $key[0];

			}
			$update['status'] = $item['code'];
			$update['save_time'] = NOW_TIME;
		}

		if ($update && $where) {
			model('stream/Video')->update($update, $where);
		}
		$video = model('stream/Video')->getOne($where);
		if (is_numeric($video['video_icon'])) {
			$video['video_icon'] = model('attach/Attach', ['getAttachUrl', $video['video_icon']])[0];
		} else {
			$video['video_icon'] = C('qiniu.cdn-url') .'/' . $video['video_icon'];
		}
		$video['source_id'] = $video['vid'];
		$video['vid'] = encrypt_id($video['vid']);
		$syncUrl = 'http://www.shante.me/api.php?api_type=live&api_version=4.6.0&app=api&mod=Public&act=getPlayback';
		self::request('post', ['data' => $video], $syncUrl);
		exit;
	}
	/**
	 * @name 主播禁言功能
	 */
	public function imDisable() {
		$st = self::checkApi(['usid']);
		if (true !== $st) {
			return $this->api_info;
		}
		$user_id = model('open/User')->getUidByUsid($this->usid);
		if ($user_id == $this->uid) {
			return ['code' => '80300', 'message' => '不能对自己禁言哦'];
		}
		//查询直播间
		$stream_id = $this->mod->getStreamId($this->uid);
		$im_model = model('open/UserImAccount');
		//查询会话,
		$conversation = $im_model->getConversation(['uid' => $this->uid, 'affix' => $stream_id, 'type' => 2]);
		if ($conversation['cid'] <= 0) {
			return getApiErrorCode('80500');
		}
		//检测是不是当前会话的管理员
		//$isadmin = model('open/ImServer')->isAdminForSation($this->uid, $this->cid);
		//if ($isadmin === true) {
		//是管理员进行的操作
		//1.检测禁言用户是否存在
		$im = [];
		if ($user_id) {
			//IM用户信息
			$im = $im_model->getImUser($user_id);
		}
		if ($im['im_uid']) {
			$map = [
				'cid' => (int) $conversation['cid'],
				'uids' => $im['im_uid'],
				'expire' => (int) $this->time ?: 0,
			];
            $res = $im_model->limitedADD($map);
			if ($res['code'] == '201') {
				return ['code' => '00000', 'message' => '禁言成功'];
			}
            
			//设置禁言失败
			return getApiErrorCode('80301');
		}
		return getApiErrorCode('80404');

	}

	/**
	 * @name 主播解除禁言
	 */
	public function imEnable() {
		$st = self::checkApi(['usid']);
		if (true !== $st) {
			return $this->api_info;
		}

		$user_id = model('open/User')->getUidByUsid($this->usid);
		if ($user_id == $this->uid) {
			return ['code' => '80300', 'message' => '不能对自己操作噢'];
		}
        //查询直播间
		$stream_id = $this->mod->getStreamId($this->uid);
        $im_model = model('open/UserImAccount');
		//查询会话,
		$conversation = $im_model->getConversation(['uid' => $this->uid, 'affix' => $stream_id, 'type' => 2]);
		if ($conversation['cid'] <= 0) {
			return getApiErrorCode('80500');
		}
		//检测是不是当前会话的管理员
		//$isadmin = model('user/ImServer')->isAdminForSation($this->uid, $this->cid);
		//if ($isadmin === true) {
		//是管理员进行的操作
		//1.检测禁言用户是否存在
		$im = [];
		if ($user_id) {
			//IM用户信息
			$im = $im_model->getImUser($user_id);
		}
		if ($im['im_uid']) {
			$map = [
				'cid' => (int) $conversation['cid'],
				'uids' => [$im['im_uid']],
			];
			$res = $im_model->limitedDELETE($map);
			if ($res['hasError'] === false) {
				return ['code' => '00000', 'message' => '解除禁言成功'];
			}
			//解除禁言失败
			return getApiErrorCode('80302');
		}
		return getApiErrorCode('80404');
	}
	/**
	 * @name 仅供调试用的获取列表方法
	 */
	public function getGagList() {
		if ($this->cid) {
			$map = ['cid' => $this->cid, 'type' => 'gag'];
			$data = model('open/UserIm')->limitedGET($map);
			return ['code' => '00000', 'data' => (object) $data['data']];
		} else {
			return ['code' => '80500', 'message' => 'cid not exists'];
		}
	}
	/**
	 * @name 获取推荐直播
	 */
	public function getRecomList($data = []) {
		if (!empty($data)) {
			$this->data = $data;
		}
		$this->count = $this->count ? $this->count : 4;
		$this->stream_uid = $this->stream_uid ? decrypt_id($this->stream_uid) : $this->uid;
		if ($this->stream_uid) {
			$data = $this->mod->getEndLiveDataDoNotClear($this->stream_uid, false, $this->count);
			$return['list'] = self::_getListData($data['uids']);
			$return['view_count'] = $data['view_count'];
		} else {
			$uids = $this->mod->getRandUids($this->count);
            //下面的判断是添加测试的假数据
            /**if(count($uids) <= 2){
                $rand_ids = [6,14,33,34];//测试数据
                $rand = array_rand($rand_ids,mt_rand(1,2));
                if(!$rand){
                    $rand = [4];
                }
                $rand = (array)$rand;
                foreach ($rand as $val) {
                    $uids[] = $rand_ids[$val];
                }
            }**/
			$return = self::_getListData($uids);
		}

		return ['code' => '00000', 'data' => $return];
	}
	/**
	 * @name 获得播放地址
	 * @access public
	 * @param int|string $uid (from api data) 用户的uid
	 * @param string $name (from api data) 获取的地址信息 多个以逗号分割: can be rtmp|hls|httpflv 默认获取所有
	 * @return array 播放地址
	 */
	public function playUrls($stream = '') {
		if (!$stream) {
			//API请求
			$st = self::checkApi();
			if ($st !== true) {
				return $this->api_info;
			}
			$stream = self::_getOneStream($this->uid);
		}
		
		return $stream['hosts'];
		if (!$stream || false !== stripos($stream->errno, '404')) {
			return getApiErrorCode('20404');
		}
		$list = [];
		if ($this->data['name']) {
			$list = explode(',', $this->data['name']);
		}
		$res = [];
		if (!empty($list)) {
			$list = arr_change_case_value($list);
			foreach ($list as $v) {
				if (!in_array($v, array('rtmp', 'hls', 'httpflv'))) {
					continue;
				}
				switch ($v) {
					case 'rtmp':
						//rtmp 播放地址
						$url = $stream->rtmpLiveUrls();
						$res['rtmp'] = $url['ORIGIN'];
						break;
					case 'hls':
						//hls播放地址
						$url = $stream->hlsLiveUrls();
						$res['hls'] = $url['ORIGIN'];
						break;
					case 'httpflv':
						//http-flv 播放地址
						$url = $stream->httpFlvLiveUrls();
						$res['httpflv'] = $url['ORIGIN'];
						break;
					default:
						break;
				}
			}
		} else {
			//返回所有的播放地址
			$res['rtmp'] = $stream->rtmpLiveUrls()['ORIGIN'];
			$res['hls'] = $stream->hlsLiveUrls()['ORIGIN'];
			$res['httpflv'] = $stream->httpFlvLiveUrls()['ORIGIN'];
		}
		return $res;
	}
	/**
	 * @name 观看直播
	 * @description 调用接口会有两种返回结果
	 *  one:如果当前查询的房间正在直播,则给出播放的地址
	 *  two:如果当前查询的房间已经结束直播,则给出随机推荐的直播间 此时的data数据中包含code=60005
	 * @param int or string stream_id 用户的UID
	 * @return array 结果信息
	 */
	public function play() {
		//权限和必须参数检验
		//$check = self::checkApi();
		//if (true !== $check) {
			//return $this->api_info;
		//}
        if($this->usid){
            $this->stream_uid = model('open/User')->getUidByUsid($this->usid);
            $this->stream_id = $this->mod->getStreamId($this->stream_uid);
        }elseif($this->stream_id){
            $this->stream_uid = $this->mod->getUidByStream($this->stream_id);
        }
        if($this->stream_uid && $this->stream_id){
    		if ($this->mod->getStreamStatus($this->stream_uid) == 1) {
    			//正在直播,给出播放地址
    			$stream = self::_getOneStream($this->stream_uid, 'object');
    			$stream_service 	= model('admin/Config')->getConfigValue(['type'=>'stream','key'=>'stream_service']);
				$hubName 			= $stream_service['hub_name'];

				$stream['hosts'] 	= [
					// "hdl" 		=> \Qiniu\Pili\HDLPlayURL("live-hdl.zhiyicx.com", $hubName, $stream['id']),
	    //             "hls" 		=> \Qiniu\Pili\HLSPlayURL("live-hls.zhiyicx.com", $hubName, $stream['id']),
	                "rtmp" 		=> \Qiniu\Pili\RTMPPlayURL(C('qiniu.rtmp-push'), $hubName, $stream['id'])
				];
    			//观看过的人数+1
    			$this->mod->addInc('view_count', 1, $this->stream_uid);
    			//取得当前直播间的聊天室
    			$im = model('open/UserImAccount')->getConversation(['affix' => $this->stream_id, 'type' => 2]);
    			if ($im['cid'] > 0) {
    				unset($im['mc']);
    				return ['code' => '00000', 'data' => ['playurls' => self::playUrls($stream), 'im' => $im,'user'=>model('open/User')->getUserInfo($this->stream_uid), 'shop' => model('stream/StreamShop')->getInstance()->getShopByStreamId($this->stream_id)]];
    			}
    		}
        }
		//返回随机推荐主播
		$return = getApiErrorCode('60005');
		$data = $this->mod->getEndLiveDataDoNotClear($this->stream_uid);

		$return['list'] = self::_getListData($data['uids']);
		$return['view_count'] = $data['view_count'] ?: 0;
		return ['code' => '00000', 'data' => $return];
	}
    /**
     * @name 查询主播的主播状态
     */
    public function getStreamStatus(){
        //权限和必须参数检验
		$check = self::checkApi(['usid']);
		if (true !== $check) {
			return $this->api_info;
		}
        $res = $this->mod->getStatusByUsid($this->usid);
        foreach($res as &$v){
            if($v['status'] == 1){
                $v['info'] = self::_getListData([$v['uid']])[0];
            }else{
                $v['info'] = (object)[];
            }
            //拉去列表的时候,直播已经关闭
            if(!$v['info']){
                $v['status'] = 0;
            }
            unset($v['uid']);
        }
        return ['code'=>'00000','data'=>$res];
    }
    /**
     * @name 播放直播
     */
    public function show(){
        if($this->usid){
            $this->uid = model('open/User')->getUidByUsid($this->usid);
        }
        zbdefine('MODEL_NAME','stream');
        $view = new \think\View([
            'theme_on' => true,
            'parse_str' => [
                '__static__' => '/public/static/stream',
                '__public__' => '/public/static/public'
            ]
        ]);
        //传递配置信息 
        $config = model('admin/Config')->getConfigValue(['type'=>'stream','key'=>'stream_3gconfig']);
        $view->assign('config',$config);
        if($this->uid && $this->mod->getStreamStatus($this->uid) == 1){
            //正在直播,给出播放地址
			$stream = self::_getOneStream($this->uid, 'object');
			//观看过的人数+1
			$this->mod->addInc('view_count', 1, $this->uid);
			//取得当前直播间的聊天室
			$im = model('open/UserImAccount')->getConversation(['affix' => $stream['id'], 'type' => 2]);
			if ($im['cid'] > 0) {
				unset($im['mc']);
				$view->assign('data',['playurls' => ['hls' => \Qiniu\Pili\HLSPlayURL(C('qiniu.hls-play'), C('qiniu.hub-name'), $stream['id'])], 'im' => $im,'user'=>model('open/User')->getUserInfo($this->uid)]);
                //获取截图封面
                		//$image_icon = $this->getSnapshot($stream);
				
                		//$image_icon = object2array($image_icon['data']['image']);
                		$view->assign('video_icon', \Qiniu\Pili\SnapshotPlayURL(C('qiniu.snap-shot'), C('qiniu.hub-name'), $stream['id']));
                
			}
            
        }
        $uname = getUname($this->uid) ? : 'TA';
        $view->assign('pageTitle',str_replace('[uname]',$uname,$config['page_title']));
        $uids = $this->mod->getRandUids($this->count ?: 20);
		$list = self::_getListData($uids);
        $list = object2array($list);
		$view->assign('list',$list);
		$view->assign('app_name',$this->app_name);
		$view->assign('deskicon_ico', getImageUrl($config['app_logo'],4) ?: "/public/static/deskicon.png");
		$view->assign('shop', (array) model('stream/StreamShop')->getInstance()->getShopByStreamId($stream['id']));
        $GLOBALS['format'] = 'html';
        
        return $view->fetch('stream@stream/show');
    }
    /**
	 * @name 查询禁言状态
	 */
	public function imIsDisable() {
		$st = self::checkApi(['usid']);
		if (true !== $st) {
			return $this->api_info;
		}
		$user_id = model('open/User')->getUidByUsid($this->usid);
		if ($user_id == $this->uid) {
			return ['code' => '00000', 'data' => ['im_status' => 0,'expire' => 0] ];
		}
		//查询直播间
		$stream_id = $this->mod->getStreamId($this->uid);
		$im_model = model('open/UserImAccount');
		//查询会话,
		$conversation = $im_model->getConversation(['uid' => $this->uid, 'affix' => $stream_id, 'type' => 2]);
		if ($conversation['cid'] <= 0) {
			return getApiErrorCode('80500');
		}
		//检测是不是当前会话的管理员
		//$isadmin = model('open/ImServer')->isAdminForSation($this->uid, $this->cid);
		//if ($isadmin === true) {
		//是管理员进行的操作
		//1.检测禁言用户是否存在
		$im = [];
		if ($user_id) {
			//IM用户信息
			$im = $im_model->getImUser($user_id);
		}
		if ($im['im_uid']) {
			$map = [
				'cid' => (int) $conversation['cid'],
			];
            $res = $im_model->limitedGET($map);
            $keys = array_keys($res['data']);
            $values = array_values($res['data']);
            $data = array_combine($keys,$values);
			if ($res['code'] == '200' && array_key_exists($im['im_uid'],$data)) {
				return ['code' => '00000', 'data' => ['im_status' => 1,'expire' => (int)$data[$im['im_uid']]]];
			}
		}
		return ['code' => '00000', 'data' => ['im_status' => 0,'expire' => 0] ];

	}

}

